<?php

namespace App\Kuafu\Order\Jobs;

use App\Kuafu\Mybank\Service\CalcBrokerage\MybankCalcOrderBrokerageService;
use App\Kuafu\Mybank\Service\CalcBrokerage\MybankCalcWaimaiBrokerageService;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Model\OrderSplitModel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;


/**
 * @description 网商分账计算队列
 *
 * @queueName {RMS-ALL-ORDER-MYBANK-CALC-QUEUE}
 */
class MybankCalcOrderPriceJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 队列名称
     *
     * @var string
     */
    public static string $QUEUE_NAME = '{RMS-ALL-ORDER-MYBANK-CALC-QUEUE}';

    /**
     * 门店id
     *
     * @var int
     */
    public int $shopId;


    /**
     * 订单id
     *
     * @var int
     */
    public string $orderId;

    /**
     * @var int 订单来源 CodeEnum::SOURCE_TYPE_SHOP ,
     */
    public int $source;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($shopId, $orderId, $source)
    {
        $this->orderId = $orderId;
        $this->shopId  = $shopId;
        $this->source  = $source;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 判断是外卖还是堂食
        try {
            if ($this->source == CodeEnum::SOURCE_TYPE_SHOP) {
                $mybankBrokerageService = new MybankCalcOrderBrokerageService($this->shopId, $this->orderId);
            } else {
                $mybankBrokerageService = new MybankCalcWaimaiBrokerageService($this->shopId, $this->orderId);
            }

            if (!$mybankBrokerageService->checkIsBind()) {
                return;
            }

            $mybankBrokerageService->calcBrokerage();

            $mybankBrokerageService->updataOrder();

        } catch (\Exception $exception) {

            Log::channel('mybank')->error('RmsOrderPay-saveBrokerageError-计算佣金失败', [
                'type'       => CodeEnum::SOURCE_TYPE_SHOP,
                'shopId'     => $this->shopId,
                'orderId'    => $this->orderId,
                'errorMsg'   => $exception->getMessage(),
                'errorTrace' => $exception->getTraceAsString(),
                'fsNotifyUids' => [
                    '3fgc8798'
                ]
            ]);
        }
    }
}
